package gupao.concurrency.api;

import gupao.concurrency.ratelimit.SemaphoreRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class XxxApiController {

    @Resource(name = "xxxApiRateLimiter")
    private SemaphoreRateLimiter semaphoreRateLimiter;

    @RequestMapping("/xxx")
    public String xxApi(){
        if(!semaphoreRateLimiter.tryAcquire()){
            return "被限流";
        }
        try{
            return doBiz();
        }finally {
            semaphoreRateLimiter.release();
        }
    }

    String doBiz(){
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
        } catch (InterruptedException e) {
        }
        return "成功执行";
    }
}
